package yns.dao.impl;

import java.util.Calendar;

import org.json.JSONArray;
import org.json.JSONObject;

import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.stereotype.Repository;

import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Filters;

import yns.dao.WeatherDao;
import yns.utility.MongoHelp;

@Repository("weatherDao")
public class WeatherDaoImpl implements WeatherDao {
	
	@Override
	public JSONArray saveWeather(JSONObject weatherJsonObject) {
		
		JSONArray result = new JSONArray();

		MongoCollection<Document> weather = MongoHelp.getMongoCollection("db","weather");

		JSONObject dbData = weatherJsonObject;
		String cityCode = dbData.getString("cityCode");
		String time = dbData.getString("time");
		
//		BasicDBObject find = new BasicDBObject();
//		find.put("time", time);
//		find.put("cityCode", cityCode);
		
		//DBObject findLast = weather.find(find, new BasicDBObject("_id", 0));
		
		Bson find = Filters.and(Filters.eq("_id", 0),
				Filters.eq("time", time), Filters.eq("cityCode", cityCode));
		Document findLast = weather.find(find).first();
		
		JSONObject findLastJsonObject = new JSONObject(findLast);
		if (findLastJsonObject == null || findLastJsonObject.isEmpty()) {

			dbData.put("cTime", Calendar.getInstance().getTimeInMillis());

			Document doc = Document.parse(dbData.toString());

			weather.insertOne(doc);

			// JSONObject resultFlag = JSONObject.fromObject(writeResult);
		}

//		DBCursor resultCursor = weather
//				.find(new BasicDBObject("cityCode", cityCode), new BasicDBObject("_id", 0))
//				.sort(new BasicDBObject("cTime", -1)).limit(24);
		
		FindIterable<Document> resultCursor = weather.find(Filters.and(Filters.eq("_id", 0),Filters.eq("cityCode", cityCode)))
				.sort(Filters.eq("cTime", -1)).limit(24);
		
		result = new JSONArray(resultCursor);
		System.out.println(result);


		return result;
	}
	
}
